package com.nanmeishu.services.im.config;


import com.nanmeishu.services.im.initializer.ServerInitializer;
import com.nanmeishu.services.im.server.NanMeiShuServer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;






@Component
public class RunConfig {

    private final Logger log = LoggerFactory.getLogger(getClass());


    @Value("${im.port}")
    private String imProp;


    @Value("${server.port}")
    private String serverPort;

    @PostConstruct
    public void nanMeiShuServer(){
        NanMeiShuServer nanMeiShuServer = new NanMeiShuServer();
        new Thread(()->{
            nanMeiShuServer.run(imProp);
        }).start();
        log.info("当前服务端口："+serverPort);
        log.info("当前web socker端口："+imProp);
    }

    /**
     * 运行程序
     */
    public void run() {
        EventLoopGroup boosGroup = new NioEventLoopGroup(1);
        EventLoopGroup workGroup = new NioEventLoopGroup();
        try{
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(boosGroup,workGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG,128)
                    .childOption(ChannelOption.SO_KEEPALIVE,true)
                    //日志服务
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ServerInitializer());
            System.out.println("------------------socket端口："+imProp+"---------------------------");
            System.out.println("------------------服务器已就绪------------------");
            ChannelFuture channelFuture = serverBootstrap.bind(Integer.parseInt(imProp)).sync();

            channelFuture.channel().closeFuture().sync();

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            boosGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }
}
